﻿/*
 * This file is part of MonoStrategy.
 *
 * Copyright (C) 2010-2011 Christoph Husse
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Authors: 
 *      # Christoph Husse
 * 
 * Also checkout our homepage: http://monostrategy.codeplex.com/
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using OpenTK;
using OpenTK.Input;

using System.Runtime.InteropServices;
using System.Threading;

#if EMBEDDED
    using OpenTK.Graphics.ES20;
#else
    using OpenTK.Graphics.OpenGL;
#endif

namespace MonoStrategy.RenderSystem
{
    public delegate void DOnSelectionChanged();

    /// <summary>
    /// This class and the whole GLRenderer-Assembly is expected to change heavily in near future, 
    /// this is why I skip many documentation at this point.
    /// </summary>
    public partial class GLRenderer 
    {
        private System.Diagnostics.Stopwatch m_Watch = new System.Diagnostics.Stopwatch();
        private readonly List<int> m_MouseState = new List<int>();
        private readonly List<OpenTK.Input.Key> m_KeyboardState = new List<OpenTK.Input.Key>();
        private readonly List<RegisteredImage> m_RegisteredImages = new List<RegisteredImage>();
        private GLProgram m_2DSceneProgram;
        
        public TerrainRenderer TerrainRenderer { get; private set; }
        public TerrainDefinition Terrain { get; set; }

        internal const Int32 SelectionGranularity = 5;
        internal Int32[] CurrentTextureIDs { get; private set; }

        public Thread RenderThread { get; private set; }
        public double AspectRatio { get; private set; }
        public bool EnableTerrainRendering { get; set; }
        public int ViewportWidth { get; private set; }
        public int ViewportHeight { get; private set; }
        public bool IsTerminated { get; private set; }
        public Point MouseXY { get; private set; }
        public IEnumerable<int> MouseState { get { lock (m_MouseState) { return m_MouseState.ToArray(); } } }
        public IEnumerable<OpenTK.Input.Key> KeyboardState { get { lock (m_KeyboardState) { return m_KeyboardState.ToArray(); } } }

        public event DNotifyHandler<GLRenderer, int> OnMouseDown;
        public event DNotifyHandler<GLRenderer, int> OnMouseUp;
        public event DNotifyHandler<GLRenderer, Point> OnMouseMove;

        public event DNotifyHandler<GLRenderer, OpenTK.Input.Key> OnKeyDown;
        public event DNotifyHandler<GLRenderer, OpenTK.Input.Key> OnKeyUp;
        public event DNotifyHandler<GLRenderer, OpenTK.Input.Key> OnKeyRepeat;

        public event DNotifyHandler<GLRenderer> OnRenderSprites;


        public static void CheckError()
        {
            CheckError("OpenGL call failed unexpectedly.");
        }

        public static void CheckError(String inMessage, params Object[] inArgs)
        {
            ErrorCode errCode = GL.GetError();

            switch (errCode)
            {
                case ErrorCode.NoError:
                    return;

                default:
                    {
                        throw new GLException(errCode, inMessage, inArgs);
                    }break;
            }
        }

        public Bitmap LoadAmbientSnapshot(String inAnimClass)
        {
            var animClass = AnimationLibrary.Instance.FindClass(inAnimClass);

            if (animClass.AmbientSet != null)
            {
                return animClass.AmbientSet.Animations.First().Frames.First().Source;
            }
            else
            {
                return animClass.Sets.First().Animations.First().Frames.First().Source;
            }
        }

        /// <summary>
        /// Even if the parameter type might seem misleading, its just because we need to register
        /// some events, so its not enough to just have the terrain array.
        /// </summary>
        /// <param name="inMovableManager"></param>
        public void AttachTerrain(TerrainDefinition inTerrain)
        {
            if (RenderThread == Thread.CurrentThread)
                throw new InvalidOperationException("This method must not be called from the rendering thread.");

            if (inTerrain == null)
                throw new ArgumentNullException();

            if (TerrainRenderer != null)
            {
                TerrainRenderer.Dispose();

                Terrain = null;
                TerrainRenderer = null;
            }

            Terrain = inTerrain;

            while (TerrainRenderer == null)
            {
                Thread.Sleep(30);
            }
        }
    }
}
